//
//  NewOrderInfoViewController.swift
//  OnceNectar
//
//  Created by 吴凌 on 2018/7/30.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Networking
import Alamofire
import PKHUD
import SwiftyJSON

class NewOrderInfoViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, BottomShadow, AddCornerUIRectCorner,OrderInfoTableViewCellDelegate,OrderLogisticsTableViewCellDelegate {
    
    @IBOutlet weak var tableView: UITableView!
    
    var model: myOrderModel?
    var isShow:Bool = false
    var timeCount: TimeInterval = 0
    var orderStatusCell: OrderStatusTableViewCell?
    
    var updatePen:Bool = true

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setUI()
        self.automaticallyAdjustsScrollViewInsets = false
        self.title = model?.statusName
        self.fetchOrderInfo(parameters: ["id":(model?.id!)!])
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func setUI() {
        tableView.register(UINib(nibName: "\(OrderStatusTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(OrderStatusTableViewCell.self)")
        tableView.register(UINib(nibName: "\(OrderPendingTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(OrderPendingTableViewCell.self)")
        tableView.register(UINib(nibName: "\(OrderLogisticsTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(OrderLogisticsTableViewCell.self)")
        tableView.register(UINib(nibName: "\(OrderAddressTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(OrderAddressTableViewCell.self)")
        tableView.register(UINib(nibName: "\(OrderInfoTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(OrderInfoTableViewCell.self)")
        tableView.register(UINib(nibName: "\(OrderListTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(OrderListTableViewCell.self)")
        tableView.register(UINib(nibName: "\(OrderListFootView.self)", bundle: nil), forHeaderFooterViewReuseIdentifier: "orderFooter")
        
    }
    
    override func setNavigation() {}
    
    
    // MARK: tableViewDatasource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if isShow{
            return 4
        }else {
            return 0
        }
    }
    // MARK: - tableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            if Int((self.model?.status)!)! > 0 && Int((self.model?.status)!)! < 4 {
                return 2
            }
        } else if section == 2 {
            return (model?.purchaseGoodsInfos?.count)!
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if Int((model?.status)!)! > 0 && Int((model?.status)!)! < 4 {
                if indexPath.row == 0 {
                    return 90
                }else {
                    return 40
                }
            }
            return 50
        } else if indexPath.section == 1 {
            return 75
        } else if indexPath.section == 2 {
            return 100
        } else if indexPath.section == 3 {
            return 260
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 2 {
            return 10
        }else {
            return 0
        }
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 2 {
            let footView :OrderListFootView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "orderFooter") as! OrderListFootView
            footView.btn1.isHidden = true
            footView.btn2.isHidden = true
            return footView
        }else {
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section ==  0{
            if Int((model?.status)!)! > 0 && Int((model?.status)!)! < 4 {
                if indexPath.row == 0 {
                    let cell = tableView.dequeueReusableCell(withIdentifier: "\(OrderPendingTableViewCell.self)") as? OrderPendingTableViewCell
                    cell?.showPending(model: self.model!,update: updatePen)
                    updatePen = false
                    return cell!
                }else {
                    let cell = tableView.dequeueReusableCell(withIdentifier: "\(OrderLogisticsTableViewCell.self)") as? OrderLogisticsTableViewCell
                    cell?.delegate = self
                    if Int((model?.status)!)! >= 2 {
                        cell?.setTitle()
                        cell?.btn.isEnabled = true
                    }
                    return cell!
                }
            }else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "\(OrderStatusTableViewCell.self)") as? OrderStatusTableViewCell
                cell?.statusLabel.text = self.model?.statusName
                cell?.amountLabel.text = "¥" + (self.model?.actualPayAmount)!
                orderStatusCell = cell
                return cell!
            }
        } else if indexPath.section ==  1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(OrderAddressTableViewCell.self)") as? OrderAddressTableViewCell
            cell?.name.text = self.model?.receiver
            cell?.tel.text = self.model?.telephoneNumber
            cell?.address.text = self.model?.deliveryAddres
            return cell!
        } else if indexPath.section ==  2{
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(OrderListTableViewCell.self)") as? OrderListTableViewCell
            let goodsModel = self.model?.purchaseGoodsInfos![indexPath.row]
            cell?.name.text = goodsModel?.goodsName
            cell?.spec.text = goodsModel?.specAndCol
            cell?.num.text = " * " + (goodsModel?.number!)!
            cell?.amount.text = "¥" + (goodsModel?.price!)!
            cell?.img.sd_setImage(with: appendUrl(suffix: (goodsModel?.imageUrl!)!), completed: nil)
            return cell!
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(OrderInfoTableViewCell.self)") as? OrderInfoTableViewCell
            cell?.delegate = self
            cell?.model = self.model
            cell?.amount.text = "¥" + (self.model?.payAmount)!
            cell?.orderNo.text = self.model?.orderNumber
            cell?.orderTime.text = self.model?.submitTime
            cell?.invoiceType.text = self.model?.invoiceType != "null" ? self.model?.invoiceType : "不开发票"
            cell?.trainAmount.text = "¥" + (self.model?.carriage)!
            cell?.payAmount.text = "¥" + (self.model?.actualPayAmount)!
            cell?.paytextLabel.text = "需支付："
            cell?.btn3.isEnabled = true
            if Int((model?.status)!)! == 0 {
                cell?.btn2.setTitle(" 取消订单 ", for: UIControlState.normal)
                cell?.btn3.setTitle(" 立即支付 ", for: UIControlState.normal)
                cell?.btn3.setTitleColor(ONColor.currencyRedColor, for: UIControlState.normal)
                cell?.btn3.layer.borderColor = ONColor.currencyRedColor.cgColor
            } else if Int((model?.status)!)! == -1 {
                cell?.btn2.isHidden = true
                cell?.btn3.setTitle(" 再次购买 ", for: UIControlState.normal)
                cell?.btn3.setTitleColor(UIColor(hex: 0xAAAAAA), for: UIControlState.normal)
                cell?.btn3.layer.borderColor = UIColor(hex: 0xAAAAAA).cgColor
            } else if Int((model?.status)!)! == 1 {
                cell?.paytextLabel.text = "总支付："
                cell?.btn2.isHidden = true
                cell?.btn3.setTitle(" 催单 ", for: UIControlState.normal)
                cell?.btn3.setTitleColor(ONColor.currencyRedColor, for: UIControlState.normal)
                cell?.btn3.layer.borderColor = ONColor.currencyRedColor.cgColor
            } else if Int((model?.status)!)! == 2 {
                cell?.paytextLabel.text = "总支付："
                cell?.btn2.setTitle(" 再次购买 ", for: UIControlState.normal)
                cell?.btn3.setTitle(" 确认收货 ", for: UIControlState.normal)
                cell?.btn3.setTitleColor(ONColor.currencyRedColor, for: UIControlState.normal)
                cell?.btn3.layer.borderColor = ONColor.currencyRedColor.cgColor
            } else if Int((model?.status)!)! == 3  {
                cell?.paytextLabel.text = "总支付："
                cell?.btn1.isHidden = false
                cell?.btn2.setTitle(" 删除订单 ", for: UIControlState.normal)
                if model?.isCommented == "1" {
                    cell?.btn3.setTitle(" 已评价 ", for: UIControlState.normal)
                    cell?.btn3.isEnabled = false
                    cell?.btn3.setTitleColor(UIColor(hex: 0xAAAAAA), for: UIControlState.normal)
                    cell?.btn3.layer.borderColor = UIColor(hex: 0xAAAAAA).cgColor
                }else {
                    cell?.btn3.setTitle(" 进行评价 ", for: UIControlState.normal)
                    cell?.btn3.setTitleColor(ONColor.currencyRedColor, for: UIControlState.normal)
                    cell?.btn3.layer.borderColor = ONColor.currencyRedColor.cgColor
                }
            } else {
                cell?.btn2.setTitle(" 删除订单 ", for: UIControlState.normal)
                cell?.btn3.setTitle(" 再次购买 ", for: UIControlState.normal)
                cell?.btn3.setTitleColor(UIColor(hex: 0xAAAAAA), for: UIControlState.normal)
                cell?.btn3.layer.borderColor = UIColor(hex: 0xAAAAAA).cgColor
            }
            return cell!
        }
    }
    
    func btn1Click(model: myOrderModel) {
        let afterSaleServiceVC = AfterSaleServiceViewController(nibName: "\(AfterSaleServiceViewController.self)", bundle: nil)
        afterSaleServiceVC.model = self.model
        navigationController?.pushViewController(afterSaleServiceVC, animated: true)
    }
    
    func btn2Click(model: myOrderModel) {
        if Int(model.status!) == 0 {
            cancelOrder(paramaters: ["id": model.id!])
        } else if Int(model.status!) == 2 {
            pushBy(model: model)
        } else if Int(model.status!)! >= 3 {
            if Int(model.status!) == 2 {
                pushLogistics()
            } else if Int(model.status!)! >= 3 {
                let alertController = UIAlertController(title: "删除订单？", message: nil, preferredStyle: .alert)
                
                let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: { (_) in
                    
                })
                let sureAction = UIAlertAction.init(title: "确定", style: .default, handler: { (_) in
                    self.deleteOrder(paramaters: ["id": model.id!])
                })
                alertController.addAction(cancel)
                alertController.addAction(sureAction)
                self.present(alertController, animated: true, completion: nil)
            }
        }
    }
    
    func pushBy(model:myOrderModel) {
        let buyNowVC = BuyNowViewController(nibName: "\(BuyNowViewController.self)", bundle: nil)
        buyNowVC.type = 3
        buyNowVC.orderNumber = model.orderNumber
        self.navigationController?.pushViewController(buyNowVC, animated: true)
    }
    
    func btn3Click(model: myOrderModel) {
        if Int(model.status!) == 0 {
            let payVC = PayViewController(nibName: "PayViewController", bundle: nil)
            payVC.titleLabel(text: "选择支付方式", nil)
            payVC.orderId = model.orderNumber
            self.navigationController?.pushViewController(payVC, animated: true)
        } else if Int(model.status!) == 1 {
            self.fetchreminder(parameters: ["id":model.id!])
        } else if Int(model.status!) == 2 {
            self.fetchConfirmReceived(parameters: ["id":model.id!])
        } else if Int(model.status!)! == 3 {
            let evaluateVC = EvaluateViewController(nibName: "\(EvaluateViewController.self)", bundle: nil)
            evaluateVC.model = self.model
            self.navigationController?.pushViewController(evaluateVC, animated: true)
        } else if Int(model.status!) == 4 {
            pushBy(model: model)
        }
    }
    
    func copyClick(orderNo: String) {
        self.showToast(msg: "复制成功")
        let pasteboard = UIPasteboard.general
        pasteboard.string = self.model?.orderNumber
    }
    
    func pushLogistics() {
        let vc = LogisticsDetailsViewController(nibName: "\(LogisticsDetailsViewController.self)", bundle: nil)
        vc.urlPath = self.model?.traceUrl
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func deleteOrder(paramaters: [String: String]) -> Void {
        let requesturl = appendUrl(suffix: deleteOrderUrl)
        Alamofire.request(requesturl, method: .get,
                          parameters: paramaters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.view.makeToast("一度蜜：" + json["message"].string!, duration: 1.5, position: .center) { didTap in
                                            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "reloadTable"), object: nil)
                                            self.navigationController?.popViewController(animated: true)
                                        }
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                                self.showToast(msg:"网络错误")
                            }
                            
        }
    }
    
    func cancelOrder(paramaters: [String: String]) -> Void {
        let requesturl = appendUrl(suffix: cancelOrderUrl)
        Alamofire.request(requesturl, method: .post,
                          parameters: paramaters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.view.makeToast("一度蜜：" + json["message"].string!, duration: 1.5, position: .center) { didTap in
                                            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "reloadTable"), object: nil)
                                            self.navigationController?.popViewController(animated: true)
                                        }
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                                self.showToast(msg:"网络错误")
                            }
                            
        }
    }
    
    /// 确认收货
    func fetchConfirmReceived(parameters: [String: String]) -> Void {

        let requesturl = "\(BaseURL)\(confirmReceived)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){

                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:json["message"].string!)
                                        self.fetchOrderInfo(parameters: parameters)
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }

        }
        
    }
    
    /// 获取info数据
    func fetchOrderInfo(parameters: [String: String]) -> Void {
        let requesturl = "\(BaseURL)\(myOrderUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        
                                        let subject = json["data"]
                                        
                                        let dic = subject.dictionary!
                                        var model = myOrderModel(fromDic: dic)
                                        model.initLabels(arr: (dic["purchaseGoodsInfos"]?.array!)!)
                                        if model.status == "0" {
                                            let payTime:Date = string2Date(dateString: model.lastPayTime!)
                                            let time = time2Time(date: payTime, another: Date())
                                            if time > 0{
                                                self.cancelOrder(paramaters: ["id": model.id!, "reason": "超时"])
                                                return;
                                            }else{
                                                self.timeCount = -time
                                            }
                                            self.setTimeLabel(timeC: self.timeCount)
                                        }
                                        self.model = model
                                        self.isShow = true
                                        self.updatePen = true
                                        self.tableView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    var timer: Timer?
    func setTimeLabel(timeC:TimeInterval) -> Void {
        self.timeCount = timeC
        let timeCount: Int = Int(timeC)
        if timeCount > 0 {
            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateCode), userInfo: nil, repeats: true)
        }
    }
    
    @objc func updateCode() -> Void {
        var title: String?
        let timeCount: Int = Int(self.timeCount)
        if timeCount > 0 {
            let time: String = time2ShowTime(stamp: self.timeCount)
            title = "剩余：" + time
        }else{
            title = ""
            if self.timer != nil && (self.timer?.isValid)! {
                self.timer?.invalidate()
            }
            self.timer = nil
        }
        orderStatusCell?.timeLabel.text = title
        self.timeCount -= TimeInterval(1)
    }
    
    /// 催单
    func fetchreminder(parameters: [String: String]) -> Void {
        let requesturl = "\(BaseURL)\(reminder)"
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        CustomShowAlertView().show(title: "小蜜已收到你的请求，正在为您抓紧处理！还请稍安勿躁~", tapClosure: {})
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }

}
